//封装开始录音事件
/**
 * 注： 依赖于mui, jq
 * 
 * 使用: window.burt_sound_record($ele) 即可 
 * **/

(function(){
	// 机器人聊天地址
	var robot_url = 'http://jisuznwd.market.alicloudapi.com/iqa/query';	
	$(function(){
		function doubleNum(num){
			num = num<10? ('0'+num): num;
			return num;
		}
		//时间转换函数 传一个时间戳
		function timeFormate(date){
			date = date || Date.now();
			date = Number(date);
			date = new Date(date);
			var recorder_timestamp = date.getTime();
			var date_month = date.getMonth()+1;  //月
			var date_date = date.getDate();   //日期
			var date_day = date.getDay();  //星期
			var date_H = doubleNum(date.getHours());  //小时
			var date_m = doubleNum(date.getMinutes());  //分钟
			
			var ret_str = null;
			var now = Date.now();
			var diffTime = now - recorder_timestamp;
			if(diffTime <24*3600*1000){  //小于一天
				ret_str = date_H+ ":" + date_m;
			}else if(diffTime <2* 24*3600*1000){  //一天到2天之间
				ret_str = '昨天 '+ date_H+ ":" + date_m;
			}else if(diffTime <7* 24*3600*1000){  //2天到7天之间
				var xingqi = null;
				switch(date_day){
					case 0: xingqi = '星期日'; break;
					case 1: xingqi = '星期一'; break;
					case 2: xingqi = '星期二'; break;
					case 3: xingqi = '星期三'; break;
					case 4: xingqi = '星期四'; break;
					case 5: xingqi = '星期五'; break;
					case 6: xingqi = '星期六'; break;
				}
				ret_str = xingqi +" "+ date_H+ ":" + date_m;
			}else{  //大于一星期
				ret_str = date_month +"-"+ date_month+" "+date_H+ ":" + date_m;
			}
			return ret_str;
		}
		
		//声音时长转换  传参毫秒
		function sound_duration(duration){
			duration = Number(duration);
			duration = parseInt(duration/1000);  //转换为秒
			var minT = parseInt(duration/60); //分钟
			var secT = parseInt(duration%60); //秒钟
			var show_txt = null;
			if(minT==0){
				show_txt = secT+'"';  //秒
			}else{
				show_txt = minT+"'"+ secT+'"';  //分秒
			}
			return show_txt;
		}
	
		function SpeechTxt(){
			this.speech =window.SpeechSynthesisUtterance? new SpeechSynthesisUtterance(): null;  //语音播放对象
			//语音对象设置
			this.init = function(){
				if(this.speech){
					//设置朗读内容和属性
					this.speech.volume = 1;
					this.speech.rate = 1;
					this.speech.pitch = 1;
				}
			}
			
			//语音播放 参数为文字
			this.speech_play = function(message){
				if(window.speechSynthesis){ //有该对象
					if(!window.speechSynthesis.speaking){  //检测是否正在说话
						this.speech.text = message;
						window.speechSynthesis.speak(this.speech);
					}else{
						window.speechSynthesis.cancel(); //移除所有语音谈话队列中的谈话。
					}
				}
			}
		}
		
		/**
		 * 参数1 jq元素对象 为装录音时提示框
		 * 参数2 jq元素对象 为装语音的盒子 chat-box
		 * **/
		var BurtSoundRecord = function($ele1, $ele2){
			
			function Fn(){
				this.obj_ele1 = $ele1; 
				this.obj_ele2 = $ele2; 
				this.currentViewObject = null;  //当前窗口对象
				this.my_speech = new SpeechTxt();
				
				
				this.init = function(){
					this.scrollToBottom();
					this.gesture();
					this.getCurrentView();
					this.bindElem();
					this.bindEvent();
					this.play_music();
					this.my_speech.init();
					this.txt_speech();
				}
				
				//手势
				this.gesture = function(){
					castapp.init();
					//初始化手势
					mui.init({
						gestureConfig: {
							tap: true, //默认为true
							doubletap: true, //默认为false
							longtap: true, //默认为false
							swipe: true, //默认为true
							drag: true, //默认为true
							hold: true, //默认为false，不监听
							release: true //默认为false，不监听
						}
					});
				}
				
				//获取当前页面对象
				this.getCurrentView = function(){
					var that = this;
					castapp.getCurrentInterface(function(currentObject){
						that.currentViewObject = currentObject;
						var type = currentObject.type;
						if(type==='robot'){ //机器人
							$('#chat_who').text('小管家');
						}
						setTimeout(function(){
							castapp.closeWaiting();  //关闭等待框
							currentObject.show();  //当前页面显示
						},3000);
					});
				}
				
				//使滚动条消息到最底部
				this.scrollToBottom = function(){
					//使滚动条滚到到底部
					var scrollHeight = this.obj_ele2.get(0).scrollHeight;
					$('.mui-scroll-wrapper').scrollTop(scrollHeight);
				}
				
				this.bindElem = function(){
					var template = `<div class="sound-content">
										<span class="msg-tip msg-tip-text msg-tip1">按住说话</span>
										<span class="msg-tip msg-tip-text msg-tip2">手指上滑，取消发送</span>
										<span class="msg-tip msg-tip-text msg-tip3">手指松开，取消发送</span>
										<span class="msg-tip msg-tip-text msg-tip4">说话时间太短</span>
										<span class="msg-tip time">
											<span class="lue">------</span>
											<span class="used_time">0:00</span>
											<span class="lue">------</span>
										</span>
										<span class="msg-tip mui-icon mui-icon-speech speech_btn"></span>
									</div>`;
					this.obj_ele1.html(template);
				}
				
				this.bindEvent = function(){
					var _self = this;
					//点击录音说话按钮，使录音说话对话框出现
					$('.grid.message span.speech').get(0).addEventListener('tap',function(e){
						e.stopPropagation();
						$('.sound-content').fadeIn();
						$('.msg-tip-text').eq(1).fadeIn(1).siblings('.msg-tip-text').fadeOut(1);
						$('.sound-content .time .used_time').text('0:00');
					});
					//点击任意处使录音对话框隐藏
					$(document).get(0).addEventListener('tap',function(e){
						e.stopPropagation();
						$('.sound-content').fadeOut();
					});
					
					
					//开始录音
					var startTimestamp = null;  //开始的时间戳
					var stopTimestamp = null;  //结束录音的时间
					var sendCancel = false;  //发送取消
					var sound_record = null;  //声音消息
					var MIN_SOUND_TIME = 800;  //录音最小时间
					var MAX_SOUND_TIME = 120000;  //录音最大时间两分钟
					var timer = null;
					$('.sound-content').get(0).addEventListener('tap',function(e){
						e.preventDefault();  //使之点击自己不隐藏
					});
					$('.speech_btn').get(0).addEventListener('touchstart',function(e){
						e.preventDefault();  //阻止冒泡事件，
						startTimestamp = Date.now();
					});
					$('.speech_btn').get(0).addEventListener('hold',function(e){
						e.preventDefault();  //使之点击自己不隐藏
						sendCancel = false;
						//提示手指上滑取消发送消息
						$('.msg-tip-text').eq(1).fadeIn(1).siblings('.msg-tip-text').fadeOut(1);
						
						mui.plusReady(function(){
							if(timer){
								clearInterval(timer);
							}
							timer = setInterval(function(){
								stopTimestamp = Date.now();
								var diffTime = stopTimestamp - startTimestamp;
								if(stopTimestamp - startTimestamp >= MAX_SOUND_TIME){
									clearInterval(timer);
									timer = null;
									if(sound_record){
										$('.sound-content').fadeOut();
										sound_record.stop();
									}
								}
								//显示录音的时间
								diffTime = parseInt(diffTime/1000);  //转换为秒
								var minT = parseInt(diffTime/60); //分钟
								var secT = parseInt(diffTime%60); //秒钟
								secT = secT<10? ('0'+secT): secT;
								var show_txt = minT+ ':' + secT;
								$('.sound-content .time .used_time').text(show_txt);
								
							},1000);
							sound_record = plus.audio.getRecorder();
							if(!sound_record){
								castapp.prompt('不能获取录音对象');
							}else{
								sound_record.record({
									filename: "_doc/audio/"
								}, function(path){
									if(sendCancel){  //取消发送
										return;
									}else{
										//可以发送消息
										//console.log(path);
										//todo
										_self.sendMsg({
											data: {
												path: path,
												time: stopTimestamp- startTimestamp
											},
											type: 'sound',
											sender: '_self'
										});
									}
								}, function(){
									castapp.prompt('录音时出现异常');
									sendCancel = false;
								});
							}
						});
					});
					$('.speech_btn').get(0).addEventListener('release',function(e){
						e.preventDefault();
						stopTimestamp = Date.now();
						//录音时间太短
						if(stopTimestamp - startTimestamp <= MIN_SOUND_TIME){
							castapp.prompt('录音时间太短');
							sendCancel = true;  //使之取消发送
						}
						if(timer){
							clearInterval(timer);
							timer = null;
						}
						$('.sound-content').fadeOut();
						sound_record.stop();
					});
					//上滑取消发送
					$('body').get(0).addEventListener('drag',function(e){
						e.stopPropagation();
						var drag_H = Math.abs(e.detail.deltaY);  //移动的绝对距离
						if(drag_H > 50){
							$('.msg-tip-text').eq(2).fadeIn(1).siblings('.msg-tip-text').fadeOut(1);
							sendCancel = true;
						}else{
							$('.msg-tip-text').eq(1).fadeIn(1).siblings('.msg-tip-text').fadeOut(1);
							sendCancel = false;
						}
					});
				}
				
				/** 发送消息
				 * obj = {
						data: {
							path: path,
							time: stopTimestamp- startTimestamp
						},
						type: 'sound',   // txt || sound || image
						sender: '_self'  //_self || others
					};
				 * **/
				this.sendMsg = function(obj){
					this.msgTemplate(obj.data, obj.type, obj.sender);
					
					if(this.currentViewObject.type == 'robot'){  //聊天对象是机器人
						this.sendMsgToRobot(obj);
					}else{  //发送给其他人
						
					}
				}
				
				//发送消息给机器人
				this.sendMsgToRobot = function(obj){
					var that = this;
					var sendTxt = null;
					switch(obj.type){
						case 'txt':
							sendTxt = obj.data;
							break;
						case 'sound': ;
						case 'image':
							sendTxt = Math.random().toString().replace('.','');
							break;
					}
					$.ajax({
						url: robot_url,
						type: 'get',
						headers:{
					        'Authorization': 'APPCODE ee87f98d712a42128421c78d72e985a0',
							'Accept': 'application/json',
							'Content-Type': 'application/json'
					    },
						data: {
						    'question': sendTxt
						},
						success:function(res){
							if(res.msg=='ok'){
								that.msgTemplate(res.result.content, 'txt', 'others');
							}else{
								castapp.prompt('小管家暂时失去音信')
							}
						},
						error:function(data){
						    castapp.prompt('请重试')
						}
					});
				}
				
				/** 生成消息模版
				 * 参数1 消息数据
				 * 参数2 消息类型  txt || sound || image
				 * 参数3 发送给的对象  _self || others
				 * **/
				
				this.msgTemplate = function(data,type='txt', sender='_self'){
					var tmp = null;
					if(sender == '_self'){
						switch(type){
							case 'txt':  
								tmp = `<div class="clear"></div>
										<div class="public-chat-box public-chat-box-my">
								    		<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt chat-txt-right">
								    			<img class='avatar' src="../images/touxiang2.jpg"/>
									    		<div class="public-chat-content">
									    			<div class="box-background">
										    			<span class="mui-icon chaticonfont chat_icon-youbian"></span>
										    			<span>${data}</span>
										    		</div>
										    		<div class="clear"></div>
									    		</div>
								    		</div>
								    	</div>`;
							    break;
							case 'sound': 
								tmp = `<div class="clear"></div>
										<div class="public-chat-box public-chat-box-my">
											<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt chat-txt-right">
								    			<img class='avatar' src="../images/touxiang2.jpg"/>
									    		<div class="public-chat-content">
									    			<div class="box-background">
										    			<span class="mui-icon chaticonfont chat_icon-youbian"></span>
										    			<span class="record sound_click" path=${data.path}>
										    				<span class="time">${sound_duration(data.time)}</span>
										    				<span class="isplaying">正在播放...</span>
										    				<span class="mui-icon chaticonfont chat_icon-fankui"></span>
										    			</span>
										    			<div class="clear"></div>
										    		</div>
									    		</div>
								    		</div>
								    	</div>`;
							    break;
							case 'image': 
								tmp = `<div class="clear"></div>
										<div class="public-chat-box public-chat-box-my">
											<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt chat-txt-right">
								    			<img class='avatar' src="../images/touxiang2.jpg"/>
									    		<div class="public-chat-content public-chat-box-bigpic">
									    			<img class='bg_pic chat_img' src="${data.path}" alt="" 
									    			data-preview-src="" data-preview-group="1"/>
									    		</div>
								    		</div>
								    	</div>`;
								break;
						}
					}else{  //对方消息
						switch(type){
							case 'txt':  
								tmp = `<div class="clear"></div>
										<div class="public-chat-box">
								    		<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt">
								    			<img class='avatar' src="../images/touxiang1.jpg"/>
									    		<div class="public-chat-content">
									    			<div class="box-background">
									    				<span class="mui-icon chaticonfont chat_icon-zuobian"></span>
										    			<span>${data}</span>
									    			</div>
									    			<div class="clear"></div>
									    		</div>
								    		</div>
								    	</div>`;
							    break;
							case 'sound': 
								tmp = `<div class="clear"></div>
										<div class="public-chat-box">
										<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt">
								    			<img class='avatar' src="../images/touxiang1.jpg"/>
									    		<div class="public-chat-content">
									    			<div class="box-background">
									    				<span class="record sound_click" path=${data.path}>
										    				<span class="time">${sound_duration(data.time)}</span>
										    				<span class="isplaying">正在播放...</span>
										    				<span class="mui-icon chaticonfont chat_icon-yuyin"></span>
										    			</span>
									    			</div>
									    		</div>
								    		</div>
								    	</div>`;
							    break;
							case 'image': 
								tmp = `<div class="clear"></div>
										<div class="public-chat-box">
											<p class='chat-time'><span>${timeFormate()}</span></p>
								    		<div class="chat-txt">
								    			<img class='avatar' src="../images/touxiang1.jpg"/>
									    		<div class="public-chat-content public-chat-box-bigpic">
									    			<img class='bg_pic chat_img' src="../images/boy1.jpg" alt="" 
									    			data-preview-src="" data-preview-group="1"/>
									    		</div>
								    		</div>
								    	</div>`;
								break;
						}
					}
					
					this.obj_ele2.append($(tmp));
					this.scrollToBottom();  //到达最底部
				}

				//点击语音消息
				this.play_music = function(){
					var that = this;
					var player = null; 
					var player_path = null;  //上一次点击播放的音乐
					this.obj_ele2.delegate('span.sound_click','click',function(e){
						e.stopPropagation();
						var $this = $(this);
						
						var sound_path = $this.attr('path');  //声音路径
						if(!sound_path){
							castapp.prompt('声音已损坏');
							return;
						}
						
						
						mui.plusReady(function(){
							if(player_path === sound_path){  //再次点击上次播放的音乐
								if(player){
									player.stop();
									player = null;
									$this.find('.isplaying').removeClass('active').siblings('span.mui-icon').removeClass('fadeout');
									return;
								}
							}else{
								player_path = sound_path;
							}
							//把其他的正在播放去掉
							that.obj_ele2.find('.isplaying.active').removeClass('active').siblings('span.mui-icon').removeClass('fadeout');;
							if(player){
								player.stop();
								player = null;
								$this.find('.isplaying').removeClass('active').siblings('span.mui-icon').removeClass('fadeout');
							}
							player = plus.audio.createPlayer(sound_path);
							//显示正在播放
							$this.find('.isplaying').addClass('active').siblings('span.mui-icon').addClass('fadeout');
							player.play(function(){
								//成功回调，语音播放完回调
								player = null;
								$this.find('.isplaying').removeClass('active').siblings('span.mui-icon').removeClass('fadeout');
							},function(){
								castapp.prompt('播放失败');
								return;
							});
						});
						
					
					});
				}
				
				//点击文本转语音播放
				this.txt_speech = function(){
					var that = this;
					if(this.speech){
						this.obj_ele2.delegate('span.txt_click','click',function(e){
							e.stopPropagation();
							var message = $(this).text().trim();
							if(message && message.length<50){
								that.my_speech.speech_play(message);
							}
						});
					}
				}
				
			}
			
			
			
			return new Fn();
		};
		
		window.burt_sound_record = BurtSoundRecord;
	});
})();
